<?php
namespace Home\Model;
use Think\Model\ViewModel;

class  DpQuestionCategoryMappingUserModel extends ViewModel {

    static private $_instance = null;
    private $allMappingData;
    private $model;

    static public function getInstance()
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new DpQuestionCategoryMappingUserModel();
            self::$_instance->getAllData();
        }
        return self::$_instance;
    }

    /**
     * @return mixed
     */
    public function getAllMappingData()
    {
        return $this->allMappingData;
    }

    private function getAllData()
    {
        $model = M('dpQuestionCategoryMappingUser');
        $this->model = $model;

        $result = $model->select();
        $this->allMappingData = $result;
    }

    public function updateQuestionCategoryMappingUser($data){

        foreach ($data as $key => $rowData){
            if ($rowData['_state'] == "removed"){
                $this->model->where("id = {$rowData['id']}")->delete();
            }
            if ($rowData['_state'] == "added"){
                $this->model->add($rowData);
            }
            if ($rowData['_state'] == "modified"){
                $this->model->save($rowData);
            }
        }

    }

    /**
     * @param $categoryIDList
     * @return array
     * 通过问题类型ID清单获取权重清单
     * 权重规则:越小管理的范围越大.
     * 每个问题都有一个权重清单,和当前权重,以便问题转发.
     */
    static function getQWeightByCategoryIDList($categoryIDList){
        $model = M('dpQuestionCategoryMappingUser');
        $result = $model->field('procedure_level')->where("category_id in ({$categoryIDList})")->order('procedure_level desc')->group('procedure_level')->select();
        $tmpList = "";
        foreach ($result as $key => $item)
        {
            $tmpList .= $item['procedure_level'].',';
        }
        $qWeightList = substr($tmpList,0,strlen($tmpList)-1);
        $qWeightArray = array('qWeightList'=>$qWeightList,
            'cQWeight'=>$result[0]['procedure_level']);//$result[0]['procedure_level']
        return $qWeightArray;
    }

    /**
     * @param $categoryIDList
     * @param $cQWeight
     * @return mixed
     * 通过问题类型ID清单和当前权重获取通知用户
     */
    static function getUserListByCategoryIDListANDQWeight($categoryIDList,$cQWeight){
        $model = M('dpQuestionCategoryMappingUser');
        $result = $model->field('user_id')->where("category_id in ({$categoryIDList}) and procedure_level= {$cQWeight}")->select();
        $tmpList = '';
        foreach ($result as $key => $item)
        {
            $tmpList .= $item['user_id'].',';
        }

        $toUserlist = substr($tmpList,0,strlen($tmpList)-1);

        return $toUserlist;
    }

}